package hang.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 航
 * @date 2024/04/12 10:30
 **/
public class ConsumerTest {
    public static void main(String[] args) {

        // 创建配置对象
        Map<String, Object> consumerConfig = new HashMap<String, Object>();
        consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, "org");

        // 创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer(consumerConfig);

        // 订阅topic
        consumer.subscribe(Collections.singletonList("test"));
        // 消费对象：消费者从 kafka 中拉取数据
        while (true){
            ConsumerRecords<String, String> datas = consumer.poll(100);
            for(ConsumerRecord<String, String> data : datas){
                System.out.println(data);
            }
        }


        // 关闭消费者
        //consumer.close();
    }
}
